<template>
  <div class="app-container">
    <el-card shadow="hover" border>
      <el-form 
        ref="addFormRef" 
        :model="form" 
        :rules="rules" 
        label-width="80px"
        class="mt-4"
      >
        <!-- 其他表单项保持不变 -->
        <el-form-item label="博客标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入博客标题" clearable />
        </el-form-item>
        <el-form-item label="URL友好标识" prop="slug">
          <el-input v-model="form.slug" placeholder="请输入URL友好标识（如：my-first-blog）" clearable />
        </el-form-item>
        <el-form-item label="博客导语/摘要" prop="excerpt">
          <el-input v-model="form.excerpt" type="textarea" placeholder="请输入博客简短摘要" rows="3" clearable />
        </el-form-item>
        
        <el-form-item label="博客正文" prop="content">
          <div class="editor-container">
            <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" class="editor-toolbar" />
            <!-- 关键：确保 :config 绑定的是响应式的 editorConfig -->
            <Editor
              v-model="form.content"
              :config="editorConfig" 
              class="editor-content"
              @onCreated="onCreated"
              @onChange="onChange"
            />
          </div>
        </el-form-item>
        
        <!-- 其他表单项保持不变 -->
        <el-form-item label="博客封面" prop="coverImageUrl">
          <image-upload v-model="form.coverImageUrl" />
        </el-form-item>
        <el-form-item label="发布状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in ver_blog_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item class="form-btn-group">
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup name="VerBlogAdd">
import { addVerBlog } from "@/api/system/verBlog";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
// 导入官网推荐的类型定义
import { getCurrentInstance, reactive, ref, toRefs, onBeforeUnmount,shallowRef } from "vue";

import { useRouter } from "vue-router";
import { getToken } from "@/utils/auth";
const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/uploadMinio");
const router = useRouter();
const { proxy } = getCurrentInstance();
const { ver_blog_status } = proxy.useDict('ver_blog_status');
const addFormRef = ref(null);
const editorRef = shallowRef()
const headers = ref({ Authorization: "Bearer " + getToken() });
// 表单数据
const data = reactive({
  form: {
    title: null,
    slug: null,
    excerpt: null,
    content: '',
    coverImageUrl: null,
    authorId: null,
    authorName: null,
    categoryId: null,
    status: 0,
    viewCount: 0
  },
  rules: {
    title: [{ required: true, message: "博客标题不能为空", trigger: "blur" }],
    slug: [{ required: true, message: "URL友好标识不能为空", trigger: "blur" }],
    content: [{ required: true, message: "博客正文不能为空", trigger: "change" }],
    status: [{ required: true, message: "发布状态不能为空", trigger: "change" }]
  }
});
const { form, rules } = toRefs(data);
 const toolbarConfig = {}
// 官网推荐：使用 IEditorConfig 类型定义，确保配置格式正确
// const editorConfig = {
//   placeholder: '请输入博客正文',
//   pasteFilter: false,
//   allowedTags: [
//     'html', 'head', 'body', 'div', 'p', 'span', 'a', 'img', 'strong', 'em',
//     'i', 'b', 'u', 's', 'h1', 'h2', 'h3', 'ul', 'ol', 'li', 'table', 'tr', 'td'
//   ],
//   allowedAttributes: {
//     '*': ['class', 'style'],
//     'a': ['href', 'target', 'rel'],
//     'img': ['src', 'alt', 'title', 'width', 'height']
//   },
//   customPaste: (editorInst, event) => {
//     const html = event.clipboardData.getData('text/html');
//     if (html) {
//       editorInst.dangerouslyInsertHtml(html);
//       event.preventDefault();
//     }
//   },
//   MENU_CONF: {
//     uploadImage:{
//           server: '/common/uploadMinio',
//           fieldName: 'file'
//     }
//   }
// };

// 官网推荐：单独配置上传图片菜单（关键步骤）
// editorConfig.value.MENU_CONF['uploadImage'] = {
//   server: '/common/uploadMinio', // 上传地址
//   fieldName: 'file',
//   headers: {
//     'Authorization': 'Bearer ' + localStorage.getItem('token')
//   },
//   timeout: 5 * 1000,
//   maxFileSize: 2 * 1024 * 1024,
//   allowedFileTypes: ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],
//   // 处理上传响应
//   customResponse: (response) => {
//     if (response.code === 200 && response.data?.url) {
//       return { url: response.data.url } // 必须返回此格式
//     } else {
//       throw new Error(response.msg || '图片上传失败')
//     }
//   },
//   onError: (error) => {
//     ElMessage.error('上传失败：' + error.message)
//   }
// }
const editorConfig = reactive({})
// 编辑器创建回调
const onCreated = (editor) => {
  editorRef.value = editor
  const newUploadConfig = {
    server: uploadImgUrl.value,
    fieldName: 'file',
    headers: headers.value,
    customInsert: (res, insertFn) => {
        console.log("res",res)
      if (res.code === 200 && res.url) {
        insertFn(res.url);
      } else {
        throw new Error(res.msg || '上传失败');
      }
    },
    onError: (error) => {
      console.error('上传失败:', error);
      proxy.$modal.msgError(`图片上传失败: ${error.message}`);
    }
  };

  // ⚠️ 关键：动态修改 MENU_CONF.uploadImage
  editor.getConfig().MENU_CONF = editor.getConfig().MENU_CONF || {};
  editor.getConfig().MENU_CONF.uploadImage = newUploadConfig;
  console.log('当前生效的上传配置:', editor.getConfig().MENU_CONF?.uploadImage)
}

// 内容变化回调
const onChange = (editorInst) => {
  form.value.content = editorInst.getHtml()
}

// 组件销毁时清理
onBeforeUnmount(() => {
        const editor = editorRef.value
        if (editor == null) return
        editor.destroy()
      })

// 提交和取消方法
const submitForm = () => {
  addFormRef.value.validate((valid) => {
    if (valid) {
      if (editor.value) {
        form.value.content = editor.value.getHtml()
      }
      addVerBlog(form.value).then(() => {
        proxy.$modal.msgSuccess("新增博客成功");
        router.push('/system/verBlog');
      }).catch((err) => {
        proxy.$modal.msgError("新增失败：" + (err.message || '网络异常'));
      });
    }
  });
};

const handleCancel = () => {
  router.push('/system/verBlog');
};
</script>

<style scoped>
/* 保持原有样式 */
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.title {
  font-size: 16px;
  font-weight: 700;
  color: #1f2937;
}
.form-btn-group {
  margin-top: 20px;
}

.editor-container {
  width: 100%;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.editor-toolbar {
  border-bottom: 1px solid #e5e7eb;
  background-color: #fff;
  padding: 6px 8px;
}

.editor-content {
  min-height: 400px;
  padding: 12px;
  background-color: #fff;
  overflow-y: auto;
}

/* 编辑器内部HTML元素的样式 */
::v-deep .w-e-text-container p {
  margin: 0 0 1em 0;
}

::v-deep .w-e-text-container h1,
::v-deep .w-e-text-container h2,
::v-deep .w-e-text-container h3 {
  margin: 1em 0;
  font-weight: bold;
}

::v-deep .w-e-text-container img {
  max-width: 100%;
  height: auto;
}

::v-deep .w-e-text-container a {
  color: #409eff;
  text-decoration: underline;
}

::v-deep .w-e-toolbar-btn:hover {
  background-color: #f3f4f6 !important;
  border-radius: 3px;
}

::v-deep .w-e-dropdown-content .w-e-dropdown-item:hover {
  background-color: #f3f4f6 !important;
}
</style>
